package com.yaowk.web.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求日志拦截器，打印请求数据
 */
@Slf4j
public class LogInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String url = httpServletRequest.getRequestURI();
        String params = JSON.toJSONString(httpServletRequest.getParameterMap(),
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue);
        String method = httpServletRequest.getMethod();
        log.info("---------------------------------------------------------------------------------");
        log.info("Request Code " + url);
        log.info("Request Url " + url);
        log.info("Request Method " + method);
        log.info("Request Params " + params);
        log.info("Request Time " + new Date());
        log.info("---------------------------------------------------------------------------------");
        Map<String,String> logMap = new HashMap<>();
        logMap.put("requestCode",url);
        logMap.put("requestUrl",url);
        logMap.put("requestMethod",method);
        logMap.put("requestParams",params);
        logMap.put("requestTime",new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
